<template>
  <div>
    <h2 class="public-title"> 银行卡管理</h2>
    <div class="bank-box clearfix" v-show="accountData.is_banded_bank">
      <div class="img-bank fl"></div>
      <!-- 银行卡 -->
      <div class="fl bank-info" v-show="(userBankedData.bank_type!=1&&userBankedData.bank_type!=2)">
        <p class="open-bank"><span class="title">开户银行</span><span class="word">{{userBankedData.bank}}</span>
        </p>
        <p><span class="title">支行名称</span><span class="word">{{cardInfo.branch}}</span></p>
        <p>
          <span class="title">开户人姓名</span><span class="word">{{cardInfo.name}}</span>
        </p>
        <p>
          <span class="title">银行账号</span>
          <span class="word" v-if="cardInfo.account">
            {{(cardInfo.account.substring(0, cardInfo.account.length-4).replace(/[\w]/g, '*') + cardInfo.account.substring(cardInfo.account.length-4, cardInfo.account.length)).replace(/\s/g,'').replace(/(.{4})/g,'$1 ')}}
          </span>
        </p>
      </div>
      <!-- 微信 -->
        <div class="fl bank-info" v-show="userBankedData.bank_type==1">
        <p class="open-bank"><span class="title">开户银行</span><span class="word">{{userBankedData.bank}}</span>
        </p>
        <p>
          <span class="title">微信账号</span>
          <span class="word" v-if="cardInfo.account">
            {{(cardInfo.account.substring(0, cardInfo.account.length-4).replace(/[\w]/g, '*') + cardInfo.account.substring(cardInfo.account.length-4, cardInfo.account.length)).replace(/\s/g,'')}}
          </span>
        </p>
        <p>
          <span class="title">微信昵称</span><span class="word">{{myNickname}}</span>
        </p>
        <p>
          <span class="title">真实姓名</span><span class="word">{{cardInfo.name}}</span>
        </p>
      </div>
      <!-- 支付宝 -->
        <div class="fl bank-info" v-show="userBankedData.bank_type==2">
        <p class="open-bank"><span class="title">开户银行</span><span class="word">{{userBankedData.bank}}</span>
        </p>
        <p>
          <span class="title">支付宝账号</span>
          <span class="word" v-if="cardInfo.account">
            {{(cardInfo.account.substring(0, cardInfo.account.length-4).replace(/[\w]/g, '*') + cardInfo.account.substring(cardInfo.account.length-4, cardInfo.account.length)).replace(/\s/g,'')}}
          </span>
        </p>
        <p>
          <span class="title">支付宝昵称</span><span class="word">{{myNickname}}</span>
        </p>
        <p>
          <span class="title">真实姓名</span><span class="word">{{cardInfo.name}}</span>
        </p>
      </div>
      <div class="pink-bth" >
        <Button :disabled="is_setBank"  @click="changCard" type="error">更换银行卡</Button>
        </div>
    </div>
    <div class="no-bind" v-show="!accountData.is_banded_bank">
      <p>您还没有绑定银行卡，<span class="bth pink-bth" @click="bindNewCard"><Button @click="changCard" type="error">立即绑定</Button></span></p>
    </div>
    <!-- 绑定银行卡 -->
    <!-- 绑定银行卡 -->
    <Modal :title="accountData.is_banded_bank?modification:binding"  v-model="bindCardShow" class="mySelf" width="490" @on-cancel="bindCardCancel">
             <div class="outerBox">
                <div class="input-box " >
                <div class="lableStyle bank-infol">开户银行</div><div class="list-box">
                  <p v-show="is_DepositBank.WeChat==1" :class="{active:wxShow}" @click="bindwx('ali','card')"><span class="icon icon-wx"></span>微信</p>
                  <p v-show="is_DepositBank.Alipay==1 " :class="{active:aliShow}" @click="bindali('wx','card')"><span class="icon icon-zfb"></span>支付宝</p>
                  <p v-show="is_DepositBank.UnionPay==1" :class="{active:cardShow}" @click="bindCard('ali','wx')"><span class="icon icon-bank"></span>银行卡</p>
                </div>
              </div>
              <!-- 绑定微信 -->
              <Form ref="wx" :model="wxForm" :rules="wxrule" :label-width="100" label-position="right" v-show="wxShow">
                <FormItem label="微信账号" prop="wxAccount">
                  <Input type="text" v-model="wxForm.wxAccount" placeholder="请输入微信账号"></Input>
                </FormItem>
                <FormItem label="昵称" prop="wxNickname">
                  <Input type="text" v-model="wxForm.wxNickname" placeholder="请输入微信昵称"></Input>
                </FormItem>
                <FormItem label="真实姓名" prop="wxName" class="hideBox">
                  <Input type="text" v-model="wxForm.wxName" :disabled="userBankedData.name?true:false" placeholder="请输入真实姓名"></Input>
                </FormItem>
                <FormItem label="手机号码" prop="tel">
                  <Input type="text" v-model="wxForm.tel" :maxlength="11" placeholder="请输入手机号码"></Input>
                </FormItem>
              </Form>
              <!-- 绑定支付宝 -->
              <Form ref="ali" :model="aliForm" :rules="alirule" :label-width="100" label-position="right" v-show="aliShow">
                <FormItem label="支付宝账号" prop="aliAccount">
                  <Input type="text" v-model="aliForm.aliAccount" placeholder="请输入支付宝账号"></Input>
                </FormItem>
                <FormItem label="昵称" prop="aliNickname">
                  <Input type="text" v-model="aliForm.aliNickname" placeholder="请输入支付宝昵称"></Input>
                </FormItem>
                <FormItem label="真实姓名" prop="aliName">
                  <Input type="text" v-model="aliForm.aliName" :disabled="userBankedData.name?true:false" placeholder="请输入真实姓名"></Input>
                </FormItem>
                <FormItem label="手机号码" prop="tel">
                  <Input type="text" v-model="aliForm.tel" :maxlength="11" placeholder="请输入手机号码"></Input>
                </FormItem>
              </Form>
              <!--绑定银行卡 -->
               <Form ref="card" :model="cardForm" :rules="cardrule" :label-width="100" label-position="right" v-show="cardShow">
                <FormItem label="持卡人" prop="cardOwner">
                  <Input type="text" v-model="cardForm.cardOwner" :disabled="userBankedData.name?true:false" placeholder="请输入持卡人姓名"></Input>
                </FormItem>
                <FormItem label="银行卡号" prop="cardNumber">
                  <Input type="text" v-model="cardForm.cardNumber" :maxlength="19" placeholder="请输入银行卡号"></Input>
                </FormItem>
                <FormItem label="发卡银行" prop="cardOfBank">
                  <Select v-model="cardForm.cardOfBank" placeholder="请选择">
                    <Option :value="d.name" v-for="(d,index) in obj" :key="index">{{d.name}}</Option>
                  </Select>
                </FormItem>
                <FormItem label="支行银行" prop="branchOfBank">
                  <Row>
                    <Col span="11">
                      <Select @on-change="mychange" type="text" placeholder="请选择" v-model="citys">
                        <Option  :value="d.name" v-for="(d,index) in citysObj" :key="index">{{d.name}}</Option>
                      </Select>
                    </Col>
                    <Col span="1">&nbsp</Col>
                    <Col span="12">
                      <Select type="text" placeholder="请选择" v-model="cardForm.branchOfBank">
                        <Option :value="d.name" v-for="(d,index) in citysObj2" :key="index">{{d.name}}</Option>
                      </Select>
                    </Col>
                  </Row>
                </FormItem>
                <FormItem label="" prop="branchName">
                  <Input type="text" v-model="cardForm.branchName" placeholder="请输入详细支行名称"></Input>
                </FormItem>
                <FormItem label="手机号码" prop="tel">
                  <Input type="text" v-model="cardForm.tel" :maxlength="11" placeholder="请输入手机号码"></Input>
                </FormItem>
              </Form>
             </div>
          <div slot="footer" align="center" v-show="wxShow">
            <Button type="error" @click="bindwxOK('wx')">确定</Button>
            <Button @click="bindwxCancle('wx')">取消</Button>
          </div>
          <div slot="footer" align="center" v-show="aliShow">
            <Button type="error" @click="bindaliOK('ali')">确定</Button>
            <Button @click="bindaliCancle('ali')">取消</Button>
          </div>
           <div slot="footer" align="center" v-show="cardShow">
            <Button type="error" @click="bindcardOK('card')">确定</Button>
            <Button @click="bindcardCancle('card')">取消</Button>
          </div>
    </Modal>
  </div>
</template>

<script>
import { jsonToString } from "@/common/js/jsonToString";
import { mapGetters, mapActions } from "vuex";
import appData from '../../../assets/json/citys.json'
export default {
  data() {
    // 绑定微信校验
    const checkwxAccount = (rule, value, callback) => {
      if (rule.required && !value) {
        callback(new Error("微信不能为空"));
      } else if (!/^[a-zA-Z0-9_-]{3,30}$/.test(value)) {
        callback(new Error("输入的微信格式错误！"));
      } else {
        callback();
      }
    };
    const checkwxNickName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("微信昵称不能为空"));
      } else {
        callback();
      }
    };
    const checkName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("真实姓名不能为空"));
      }else {
        callback();
      }
    };
    const checkTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号码不能为空"));
      } else if (!/^[0-9]{11}$/.test(value)) {
        callback(new Error("输入的手机号码格式错误！"));
      } else {
        callback();
      }
    };
    //绑定支付宝校验
    const checkaliAccount = (rule, value, callback) => {
      if (rule.required && !value) {
        callback(new Error("支付宝账号不能为空"));
      } else if (!/^[a-zA-Z0-9_-]{3,30}$/.test(value)) {
        callback(new Error("输入的支付宝格式错误！"));
      } else {
        callback();
      }
    };
    const checkaliNickName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("支付宝昵称不能为空"));
      } else {
        callback();
      }
    };
    //绑定银行卡校验
    const checkCardOwner = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("真实姓名不能为空"));
      }else {
        callback();
      }
    };
    const checkCardNumber = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入银行卡号"));
      } else if (!/^([1-9]{1})(\d{15,18})$/.test(value)) {
				// callback();
        callback(new Error("请输入16-19位卡号"));
      } else {
        callback();
      }
    };
    const checkCardOfBank = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择发卡银行"));
      } else {
        callback();
      }
    };
    const checkBranchOfBank = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择发卡省市"));
      } else {
        callback();
      }
    };
    const checkBranchName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写发卡支行详细名称"));
      } else {
        callback();
      }
    };
    const checkTelephoneNumber = (rule, value, callback) => {
      if (value !== "" && !/^[0-9]{11}$/.test(value)) {
        callback(new Error("输入的手机号码格式错误！"));
      } else {
        callback();
      }
    };
    return {
      modification:"修改银行卡",
      binding:"绑定银行卡",
      is_setBank:false,
      Alipay:"",
      is_DepositBank:[],//开户银行显示
      myNickname:"",
      citys:[],
      obj:[],
      citysObj:[],
      citysObj2:[],
      userAccounData: {},
      userBankedData: {},
      cardInfo: {},
      userData: "",
      bindCardShow: false,
      // 绑定微信
      wxShow: false,
      wxForm: {
        wxAccount: "",
        wxNickname: "",
        wxName: "",
        tel: "",
      },
      wxrule: {
        wxAccount: [{ required: true, validator: checkwxAccount, trigger: "blur" }],
        wxNickname: [{ required: true, validator: checkwxNickName, trigger: "blur" }],
        wxName: [{ required: true, validator: checkName, trigger: "blur" }],
        tel: [{ required: true, validator: checkTel, trigger: "blur" }]
      },
      //绑定支付宝
      aliShow: false,
      aliForm: {
        aliAccount: "",
        aliNickname: "",
        aliName: "",
        tel: ""
      },
      alirule: {
        aliAccount: [{ required: true, validator: checkaliAccount, trigger: "blur" }],
        aliNickname: [{ required: true, validator: checkaliNickName, trigger: "blur" }],
        aliName: [{ required: true, validator: checkName, trigger: "blur" }],
        tel: [{ required: true, validator: checkTel, trigger: "blur" }]
      },
      //绑定银行卡
      cardShow: false,
      cardForm: {
        cardOwner: "",
        cardNumber: "",
        cardOfBank: "",
        branchOfBank: "",
        branchName: "",
        tel: ""
      },
      cardrule: {
        cardOwner: [{ required: true, validator: checkCardOwner, trigger: "blur" }],
        cardNumber: [{ required: true, validator: checkCardNumber, trigger: "blur" }],
        cardOfBank: [{ required: true, validator: checkCardOfBank, trigger: "blur" }],
        branchOfBank: [{ required: true, validator: checkBranchOfBank, trigger: "blur" }],
        branchName: [{ required: true, validator: checkBranchName, trigger: "blur" }],
        tel: [{ validator: checkTelephoneNumber, trigger: "blur" }]
      }
    };
  },
  computed: {
    ...mapGetters(["bankedData", "accountData", "userInfo"])
  },
  created() {
    this.getUserIsBindCard();
    this.userAccounData = this.accountData;
    this.$http.post("?m=api&c=bank&a=getConfigBanks").then(res=>{
      this.obj = res.data.list
    })
    this.citysObj = appData
    this.$http.post('?m=api&c=bank&a=switchCardType').then(res=>{
      this.is_DepositBank = res.data.data;
      if (this.is_DepositBank.WeChat == 1) {
        this.wxShow = true;
      } else if (this.is_DepositBank.Alipay == 1) {
        this.aliShow = true;
      } else {
        this.cardShow = true;
      }
    })
  },
  methods: {
    ...mapActions(["SET_BANKED_DATA", "SET_ACCOUNT_DATA", "SET_USER_INFO_DATA"]),
    bindCardCancel() { //关闭清空数据
      if (this.wxShow) {
        this.wxForm.wxAccount = ''
        this.wxForm.wxNickname = ''
        this.wxForm.tel = ''
        return
      }
      if (this.aliShow) {
        this.aliForm.aliAccount = ''
        this.aliForm.aliNickname = ''
        this.aliForm.tel = ''
        return
      }
      if (this.cardShow) {
        this.cardForm.cardNumber = ''
        this.cardForm.cardOfBank = ''
        this.citys = ''
        this.cardForm.branchOfBank = ''
        this.cardForm.branchName = ''
        this.cardForm.tel = ''
        return
      }      
    },
    //获取绑定银行卡信息银行卡信息
    mychange(){
      this.citysObj2 = []
      var that = this;
			setTimeout(function(){
				appData.forEach((val,i) => {
          if(that.citys == val.name){
            that.citysObj2 = val.city
          }
        });
			}, 20)
    },
    getUserIsBindCard: function() {
      var params = {
        token: localStorage.getItem("token")
      };
      var that = this;
      this.$http.post(this.urlRequest + "?m=api&c=bank&a=getUserBank", jsonToString(params)).then(res => {
          console.log(res.data.is_setBank,'userBankedData')
          if (res.data.is_setBank !== 0) {
            this.is_setBank = false
          } else {
            this.is_setBank = true
          }
          that.userBankedData = res.data;
          if (res.data.name) {
            this.wxForm.wxName = res.data.name
            this.aliForm.aliName = res.data.name
            this.cardForm.cardOwner = res.data.name
          }
          that.cardInfo = res.data;
          if (that.userBankedData.bank_type == 1 || that.userBankedData.bank_type == 2) {
            that.myNickname = JSON.parse(that.cardInfo.branch).nickname;
          }
          localStorage.setItem("bankedData", JSON.stringify(res.data));
          that.SET_BANKED_DATA({
            obj: res.data
          });
        });
      // }
    },
    bindNewCard: function() {
      this.bindCardShow = true;
    },
    bindwx: function(item1,item2) {
      this.bindCardCancel()
      this.wxShow = true;
      this.aliShow = false;
      this.cardShow = false;
    },
    bindali: function(item1,item2) {
      this.bindCardCancel()
      this.wxShow = false;
      this.aliShow = true;
      this.cardShow = false;
    },
    bindCard: function(item1,item2) {
      this.bindCardCancel()
      this.wxShow = false;
      this.aliShow = false;
      this.cardShow = true;
    },
    //确定绑定微信
    bindwxOK(wx) {
      var that = this
      this.$refs[wx].validate(valid => {
        if (valid) {
          var params = {
            token: localStorage.getItem("token"),
            name: this.wxForm.wxName,
            account: this.wxForm.wxAccount,
            nickname: this.wxForm.wxNickname,
            mobile: this.wxForm.tel,
            flag_b: 1
          };
          this.$http.post(this.urlRequest + "?m=api&c=bank&a=bindWeChatAndAlipay",jsonToString(params)).then(res => {
            console.log(res);
            if (res.data.ret_msg == 0) {
              that.bindCardShow = false;
              that.$Message.success("绑定微信成功！");
              that.userAccounData.is_banded_bank = "1";
              this.bindCardCancel();
              let temp = this.userInfo;
              temp["realname"] = this.wxForm.wxName;
              this.SET_USER_INFO_DATA({
                  Obj: temp
              });
              that.SET_ACCOUNT_DATA({
                Obj: that.userAccounData
              });
              that.getUserIsBindCard();
            } else {
              that.$Message.error(res.data.ret_msg);
            }
          });
        }
      });
    },
    //取消绑定微信
    bindwxCancle(wx) {
      this.bindCardCancel()
      this.bindCardShow = false;
    },
    // 确定绑定支付宝
    bindaliOK(ali) {
      this.$refs[ali].validate(valid => {
        if (valid) {
          var params = {
            token: localStorage.getItem("token"),
            name: this.aliForm.aliName,
            account: this.aliForm.aliAccount,
            nickname: this.aliForm.aliNickname,
            mobile: this.aliForm.tel,
            flag_b: 2
          };
          this.$http.post(this.urlRequest + "?m=api&c=bank&a=bindWeChatAndAlipay",jsonToString(params)).then(res => {
            if (res.data.ret_msg == 0) {
              this.bindCardShow = false;
              this.$Message.success("绑定支付宝成功！");
              this.userAccounData.is_banded_bank = "1";
              this.bindCardCancel();
              let temp = this.userInfo;
              temp["realname"] = this.aliForm.aliName;
              this.SET_USER_INFO_DATA({
                  Obj: temp
              });
              this.SET_ACCOUNT_DATA({
                Obj: this.userAccounData
              });
              this.getUserIsBindCard();
            } else {
              this.$Message.error(res.data.ret_msg);
            }
          });
        }
      });
    },
    //取消绑定支付宝
    bindaliCancle(ali) {
      this.bindCardCancel()
      this.bindCardShow = false;
    },
    //确定绑定银行卡
    bindcardOK(card) {
      this.$http.post("?m=api&c=bank&a=getConfigBanks").then(res => {
        if (res.data.status == 0) {
          res.data.list.forEach(val => {
            if (val.name == this.cardForm.cardOfBank) {
              this.cardForm.cardOfBank = val.id
            }
          });
          this.$refs[card].validate(valid => {
            if (valid) {
              var params = {
                cardForm: {
                  cardOwner: "",
                  cardNumber: "",
                  cardOfBank: "",
                  branchOfBank: "",
                  branchName: "",
                  tel: ""
                },
                token: localStorage.getItem("token"),
                name: this.cardForm.cardOwner,
                account: this.cardForm.cardNumber,
                bank: this.cardForm.cardOfBank,
                branch: this.citys + ' ' + this.cardForm.branchOfBank + ' ' + this.cardForm.branchName,
                mobile: this.cardForm.tel
              };
              console.log(params)
              this.$http.post(this.urlRequest + "?m=api&c=bank&a=bank", jsonToString(params)).then(res => {
                if (res.data.ret_msg == 0) {
                  this.bindCardShow = false;
                  this.$Message.success("绑定银行卡成功！");
                  this.userAccounData.is_banded_bank = "1";
                  this.bindCardCancel();
                  let temp = this.userInfo;
					        temp["realname"] = this.cardForm.cardOwner
                  this.SET_USER_INFO_DATA({
                      Obj: temp
                  });
                  this.SET_ACCOUNT_DATA({
                    Obj: this.userAccounData
                  });
                  this.getUserIsBindCard();
                } else {
                  this.$Message.error(res.data.ret_msg);
                }
              });
            }
          });
        } else {
          this.$Message.error(res.data.ret_msg);
        }
      })
    },
    //取消绑定银行卡
    bindcardCancle(card) {
      this.bindCardCancel()
      this.bindCardShow = false;
    },
    //更换银行卡
    changCard: function() {
      this.bindCardShow = true;
    }
  },
  watch: {
    '$route'(){
      this.getUserIsBindCard();
      this.userAccounData = this.accountData;
      this.$http.post("?m=api&c=bank&a=getConfigBanks").then(res=>{
        this.obj = res.data.list
      })
      this.citysObj = appData
      this.$http.post('?m=api&c=bank&a=switchCardType').then(res=>{
        this.is_DepositBank = res.data.data
        if (this.is_DepositBank.WeChat == 1) {
          this.wxShow = true;
        } else if (this.is_DepositBank.Alipay == 1) {
          this.aliShow = true;
        } else {
          this.cardShow = true;
        }
      })
    },
    citys(val) {
      // if (val) {
      //   this.citysObj2 = '';
      // }
    }
  }
};
</script>
<style scoped>
.fixed-pas {
  width: 500px;
}
.ivu-form .ivu-form-item-label {
  font-size: 14px;
}
.input-box {
  width: 394px;
}
.input-box .lableStyle {
  width: 94px !important;
  margin-right: 12px;
  height: 34px;
  line-height: 34px;
  padding-right: 0px;
  font-size: 15px !important;
  text-align: right;
}
.list-box {
  width: 314px;
}
.list-box p {
  float: left;
  font-size: 15px;
  height: 34px;
  line-height: 34px;
  border-radius: 1px;
  padding: 0 9px;
  background-color: #ffffff;
  box-shadow: 0 1px 1px 0 rgba(255, 255, 255, 0.11);
  border: solid 1px #e6e3da;
  cursor: pointer;
}
.list-box p {
  margin-right: 9px;
}
.input-box {
  display: flex;
}
.outerBox {
  padding: 18px 26px 0 26px;
}

.icon-wx {
  display: inline-block;
  width: 18px;
  height: 18px;
  /* background: url("../../../assets//images/spirt.png") no-repeat -29px -190px; */
  margin: 0 5px;
}
.icon-zfb {
  display: inline-block;
  width: 18px;
  height: 18px;
  /* background: url("../../../assets//images/spirt.png") no-repeat -29px -167px; */
  margin: 0 5px;
}
.icon-bank {
  display: inline-block;
  width: 18px;
  height: 18px;
  /* background: url("../../../assets//images/spirt.png") no-repeat -29px -215px; */
  margin: 0 5px;
}
p.active {
  border: 1px solid #4a90e2;
}
</style>
<style>
.ivu-form .ivu-form-item-label {
  /* font-size: 15px !important; */
}
.ivu-modal-header p,
.ivu-modal-header-inner {
  font-size: 16px;
}
.pink-bth {
  cursor: pointer;
}
.activeStyle:hover {
  color: #f3596a !important;
}
</style>

<style>

</style>





// WEBPACK FOOTER //
// src/components/PersonalCenter/cardManager/cardManager.vue